package com.example.vo;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 自定义响应结构
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class SysResult implements Serializable {

	private static final long serialVersionUID = 1L;

	protected static final ObjectMapper MAPPER = new ObjectMapper();

	public static final int STATUS_SUCCEED = 200;
	public static final int STATUS_PARAMETER_ERROR = 400;
	public static final int STATUS_UNAUTHORIZED = 401;
	public static final int STATUS_PERMISSION_DENIED = 402;
	public static final int STATUS_FAILED = 403;
	public static final int STATUS_SERVER_ERROR = 500;
	protected static final Map<Integer, String> MESSAGES;

	static {
		MESSAGES = new HashMap<>();
		MESSAGES.put(STATUS_SUCCEED, "OK");
		MESSAGES.put(STATUS_UNAUTHORIZED, "未登陆");
		MESSAGES.put(STATUS_PARAMETER_ERROR, "参数错误");
		MESSAGES.put(STATUS_PERMISSION_DENIED, "权限不足");
		MESSAGES.put(STATUS_SERVER_ERROR, "服务器错误");
		MESSAGES.put(STATUS_FAILED, "操作失败");
	}

	/**
	 * 响应状态码
	 */
	protected Integer status;

	/**
	 * 响应消息
	 */
	protected String msg;

	public SysResult() {
	}

	public SysResult(Integer status, String msg) {
		this.status = status;
		this.msg = msg;
	}
	
	public SysResult(Integer status) {
		this(status, MESSAGES.get(status));
	}

	public static SysResult build(Integer status) {
		return new SysResult(status);
	}
	
	public static SysResult build(Integer status, String msg) {
		return new SysResult(status, msg);
	}

	

	public Boolean isOk() {
		return this.status == STATUS_SUCCEED;
	}

	public Integer getStatus() {
		return status;
	}

	public void setStatus(Integer status) {
		this.status = status;
	}

	public String getMsg() {
		return msg != null ? msg : MESSAGES.get(this.status);
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public static SysResult ok() {
		return new SysResult(STATUS_SUCCEED);
	}
	
	private static SysResult build(int status, String msg) {
		return new SysResult(status, msg);
	}

	/**
	 * 将json结果集转化为SysResult对象
	 * @param jsonData json数据
	 * @return
	 */
	private static SysResult format(String jsonData) {
		try {
			return MAPPER.readValue(jsonData, SysResult.class);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public String toString() {
		return "SysResult [status=" + status + ", msg=" + msg + "]";
	}
	
}
